package com.atguigu.netty.buf;

import java.nio.ByteBuffer;

/**
 * @author zhangcheng
 * @date 2024/3/20 22:57
 * @description
 */
public class ByteBufferDemo {

    public static void main(String[] args) {

        ByteBuffer buffer = ByteBuffer.allocate(128);

        String content = "hello netty";
        buffer.put(content.getBytes());

        System.out.println("after netty readableBytes = " + buffer.position());
        System.out.println("after netty readerIndex = " + 0);
        System.out.println("after netty writerIndex = " + buffer.position());


        buffer.put("666".getBytes());

        System.out.println("after 666 readableBytes = " + buffer.position());
        System.out.println("after 666 readerIndex = " + 0);
        System.out.println("after 666 writerIndex = " + buffer.position());

//        buffer.mark();
        int position = buffer.position();
        int limit = buffer.limit();

        //read之前需要flip 因为我们要从头读
        buffer.flip();

        while (buffer.position() < buffer.limit()){
            System.out.println(Character.toChars(buffer.get()));
        }

        System.out.println("after readByte readableBytes = " + (buffer.limit() - buffer.position()));
        System.out.println("after readByte readerIndex = " + 0);
        System.out.println("after readByte writerIndex = " + buffer.position());


        buffer.position(position);
        buffer.limit(limit);

        System.out.println("after resetReaderIndex readableBytes = " + buffer.position());
        System.out.println("after resetReaderIndex readerIndex = " + 0);
        System.out.println("after resetReaderIndex writerIndex = " + buffer.position());

        buffer.clear();

        System.out.println("after clear readableBytes = " + buffer.position());
        System.out.println("after clear readerIndex = " + buffer.position());
        System.out.println("after clear writerIndex = " + buffer.position());

    }
}
